import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:wanxiang_app/bean/simple_entity.dart';
import 'package:wanxiang_app/utils/common.dart';
import 'package:wanxiang_app/utils/user_util.dart';
import '../../bean/order_list_entity.dart';
import '../../utils/constant.dart';
import '../../utils/network_manager.dart';
import '../../utils/network_url.dart';
import '../../utils/toast_util.dart';
import '../../widgets/myappbar.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:easy_refresh/easy_refresh.dart';
import 'package:nim_core/nim_core.dart';
import '../../widgets/simple_dialog.dart';
import '../msg/group.dart';
import 'charge.dart';
import 'orderDetail.dart';

class OrderssController extends GetxController{
  @override
  void onInit() {
    super.onInit();
    clickTabIndex = Get.arguments;
    _getService();
  }
  @override
  void onClose() {
    super.onClose();
  }
  var baopeiRate = 0.1.obs;
  int clickTabIndex = 0;
  List<Map> tabs=[{'name':'全部','value':''},{'name':'待支付','value':'11'},
    // {'name':'交易中','value':'12'},
    {'name':'交易中','value':'13'},{'name':'已取消','value':'14'}
    ,{'name':'已成交','value':'15'},{'name':'已退款','value':'16'}];
  List<OrderListData> list = [];
  List<OrderListData> allList = [];
  void _getService(){
    DioManager.getInstance().post(ServiceUrl.orderList,{
      "user_name": UserUtil.getUSER()?.userName,
    }, (data) async {
      OrderListEntity bannerEntity = OrderListEntity.fromJson(jsonDecode(data));
      allList = bannerEntity.data;
      _filterData();
      update();
    }, (error) {
      ToastUtil.show(error);
    });
  }

  _filterData(){
    if(clickTabIndex==0){
      list = allList;
    }else{
      list = [];
      for(var item in allList){
        if(clickTabIndex==1){
          if(item.status == 11){
            list.add(item);
          }
        }else if(clickTabIndex==2){
          if(item.status == 12 || item.status == 13){
            list.add(item);
          }
        }else if(clickTabIndex==3){
          if(item.status == 14){
            list.add(item);
          }
        }else if(clickTabIndex==4){
          if(item.status == 15){
            list.add(item);
          }
        }else if(clickTabIndex==5){
          if(item.status == 16){
            list.add(item);
          }
        }
      }
    }
  }

  void getAddTeams(OrderListData item) {

    DioManager.getInstance().getRequest2(ServiceUrl.getAddTeams, {
      'channel_id':item.channelId.toString(),
      'order_id':item.id.toString(),
    },(data) async {
          SimpleEntity bannerEntity = SimpleEntity.fromJson(jsonDecode(data));
          if(bannerEntity.code==200){
            _queryTeam(bannerEntity.data);
          }
        }, (error) {
          ToastUtil.show(error);
        });
  }
  _queryTeam(teamId) async {
    NIMResult<NIMTeam> aa= await NimCore.instance.teamService.queryTeam(teamId);
    if(aa.isSuccess){
      print('---------------nickName'+aa.data!.name!+'    servicePhoto='+aa.data!.icon!);
      print(aa);
      Get.to(() => GroupPage(),
          arguments: {
            'sessionId':teamId,
            'nickName':aa.data!.name,
            'servicePhoto':aa.data!.icon,
            'account':teamId,
          },
          preventDuplicates: false)
      ;
    }

  }
  void _cancelOrder(context ,cid,oid){

    showDialog(context: context, builder: (BuildContext context1) {
      return MySimpleDialog(callBack: (String content) {
        if(content == 'cancel'){
          Navigator.pop(context1);
        }else if(content == 'sure'){
          Navigator.pop(context1);
          DioManager.getInstance().post(ServiceUrl.cancelOrder,{
            "user_name": UserUtil.getUSER()?.userName,
            "channel_id": cid.toString(),
            "order_id": oid.toString()
          }, (data) async {
            SimpleEntity bannerEntity = SimpleEntity.fromJson(jsonDecode(data));
            ToastUtil.show(bannerEntity.msg);
            _getService();
            update();
          }, (error) {
            ToastUtil.show(error);
          });
        }
      },
        msg: "是否立即取消订单？",
        sureText: "确定",
      );
    });
  }

  void _sureOrder(context,cid,oid){
    showDialog(context: context, builder: (BuildContext context1) {
      return MySimpleDialog(callBack: (String content) {
        if(content == 'cancel'){
          Navigator.pop(context1);
        }else if(content == 'sure'){
          Navigator.pop(context1);
          DioManager.getInstance().post(ServiceUrl.sureOrder,{
            "user_name": UserUtil.getUSER()?.userName,
            "channel_id": cid.toString(),
            "order_id": oid.toString()
          }, (data) async {
            SimpleEntity bannerEntity = SimpleEntity.fromJson(jsonDecode(data));
            ToastUtil.show(bannerEntity.msg);
            _getService();
            update();
          }, (error) {
            ToastUtil.show(error);
          });
        }
      },
        msg: "是否确认收货？",
        sureText: "确定",
      );
    });
  }

  void _changeBind(context,cid,oid){
    showDialog(context: context, builder: (BuildContext context1) {
      return MySimpleDialog(callBack: (String content) {
        if(content == 'cancel'){
          Navigator.pop(context1);
        }else if(content == 'sure'){
          Navigator.pop(context1);
          DioManager.getInstance().post(ServiceUrl.getChangeBinding,{
            "user_name": UserUtil.getUSER()?.userName,
            "channel_id": cid.toString(),
            "order_id": oid.toString()
          }, (data) async {
            SimpleEntity bannerEntity = SimpleEntity.fromJson(jsonDecode(data));
            ToastUtil.show(bannerEntity.msg);
            _getService();
            update();
          }, (error) {
            ToastUtil.show(error);
          });
        }
      },
        msg: "是否确定已换绑完成？(确定之后2小时将自动收货)",
        sureText: "确定",
      );
    });
  }

  void _buyNow(context,cid,gid){
    showDialog(context: context, builder: (BuildContext context1) {
      return MySimpleDialog(callBack: (String content) {
        if(content == 'cancel'){
          Navigator.pop(context1);
        }else if(content == 'sure'){
          Navigator.pop(context1);
          DioManager.getInstance().post(ServiceUrl.sureOrder,{
            "user_name": UserUtil.getUSER()?.userName,
            "channel_id": cid.toString(),
            "goods_id": gid.toString(),
            "buy_type":3
          }, (data) async {
            SimpleEntity bannerEntity = SimpleEntity.fromJson(jsonDecode(data));
            ToastUtil.show(bannerEntity.msg);
            _getService();
            update();
          }, (error) {
            ToastUtil.show(error);
          });
        }
      },
        msg: "是否立即支付该订单？",
        sureText: "确定",
      );
    });
  }
  EasyRefreshController easyRefreshController = EasyRefreshController(
    controlFinishRefresh: true,
    controlFinishLoad: true,
  );
}


class OrdersBuyPage extends GetView<OrderssController>  {
  late OrderssController controller ;
  late BuildContext context ;
  @override
  Widget build(BuildContext context1) {
    Get.lazyPut<OrderssController>(() => OrderssController());
    controller = Get.find();
    context = context1;

    return GetBuilder<OrderssController>(
      builder: (_){
        return  Scaffold(
            appBar: MyAppBar(context: context, title: '我的订单',hasLeading: true,),
            backgroundColor: Colors.white,
            body:_content());
      },
    );
  }


  Widget _empty(){
    return Container(
      margin: EdgeInsets.only(top: 30.h),
      alignment: Alignment.center,
      child: Image.asset(Constant.IMG_BASE+'empty.png',width: 150.w,height: 127.h,),
    );
  }

  Widget _content(){
    return Container(
      child: Column(
        children: [
          Container(
            margin: EdgeInsets.only(left:16.w,right: 16.w ,top: 16.h),
            child:   Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: tabsItems(),
            )
          ),
          _line(),
          controller.list.length==0?_empty():
          Container(
            width: MediaQuery.of(context).size.width,
            height: MediaQuery.of(context).size.height - 8.h - 130.h,
            child: _refresh(),
          )
        ],
      ),
    );
  }
  
  Widget _line(){
    return Container(
      width: MediaQuery.of(context).size.width,
      color: Color(0xFFF7F8FC),
      height: 8.h,
    );
  }

  List<Widget> tabsItems(){
    List<Widget> aa = [];
    for(int i =0 ;i<controller.tabs.length;i++){
      aa.add(_tabItem(controller.tabs[i]['name'],i));
    }
    return aa;
  }

  Widget _tabItem(name,index){
    return InkWell(
      onTap: (){
        controller.clickTabIndex = index;
        controller._filterData();
        controller.update();
      },
      child: Column(
        children: [
          Text(name,style: TextStyle(color:Color(0xFF333333),fontSize: 14.sp),),
          SizedBox(height: 10.h,),
          index == controller.clickTabIndex?
          Container(
            width: 27.w,
            height: 2.h,
            color: Color(0xFF007BE5),
          ):Container(height: 2.h,)
        ],
      )
    ) ;
  }

  Widget _refresh(){
    return   Scaffold(
        backgroundColor: Colors.white,
        body:  EasyRefresh(
          header: ClassicHeader(
            dragText: 'Pull to refresh'.tr,
            armedText: 'Release ready'.tr,
            readyText: 'Refreshing...'.tr,
            processingText: 'Refreshing...'.tr,
            processedText: 'Succeeded'.tr,
            noMoreText: 'No more'.tr,
            failedText: 'Failed'.tr,
            messageText: 'Last updated at %T'.tr,
          ),
          footer: ClassicFooter(
            dragText: 'Pull to load'.tr,
            armedText: 'Release ready'.tr,
            readyText: 'Loading...'.tr,
            processingText: 'Loading...'.tr,
            processedText: 'Succeeded'.tr,
            noMoreText: 'No more'.tr,
            failedText: 'Failed'.tr,
            messageText: 'Last updated at %T'.tr,
          ),
          controller: controller.easyRefreshController,
          onRefresh: () async {
          },
          onLoad: () async {
            controller.easyRefreshController.finishLoad(
                IndicatorResult.noMore );
          },
          child: ListView.separated(
            itemBuilder: (context, index) {
              return _gameItems(controller.list[index]);
            }, separatorBuilder: (BuildContext context, int index) {
              return Container(height: 8.h,color: Color(0xFFF7F8FC),);
          }, itemCount: controller.list.length,
          ),
        ));
  }

  Widget _gameItems(OrderListData item){
    return
      InkWell(
          onTap: (){
            Get.to(()=>OrderDetailPage(),arguments: {
              'channel_id':item.channelId.toString(),
              'order_id':item.id.toString()
            },preventDuplicates:false)?.then((value) => {
              controller._getService()
            });
          },
          child: Container(
            margin: EdgeInsets.only(left: 16.w,right: 13.w,top: 24.h),
            child:
            Column(
              children: [
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Text('订单号：${item.id}',style: TextStyle(
                      color: Color(0xFF333333),
                      fontWeight: FontWeight.bold,
                      fontSize: 12.sp
                    ),),
                    Text(Common.orderStatusToText(item.status),style: TextStyle(
                        color: Color(0xFF007BE5),
                        fontSize: 12.sp
                    ),),
                  ],
                ),
                Container(
                  margin: EdgeInsets.only(top: 13.h,bottom: 13.h),
                  color: Color(0xFFF3F3F3),
                  height: 1.h,
                ),
                Row(
                  children: [
                    Container(
                        width: 100.w,
                        height: 78.h,
                        child: Stack(
                          children: [

                            ClipRRect(
                                borderRadius: BorderRadius.circular(10.r),
                              child:  Image.network(Common.realPicPath(item.imgUrl),width: 100.w,height: 78.h,fit: BoxFit.cover,)
                            ),
                            item.isBaopei == 1?
                            _officer():Container(),
                          ],
                        )

                    ),
                    SizedBox(width: 14.w,),
                    Container(
                        width: MediaQuery.of(context).size.width - 29.w - 14.w - 100.w,
                        child:  Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text(item.title,
                              style: TextStyle(color: Color(0xFF333333),fontSize: 14.sp,),maxLines: 1,    textAlign: TextAlign.left,
                              overflow: TextOverflow.ellipsis,),
                            SizedBox(height: 10.h,),
                            Text('区服：${item.categoryText}',style: TextStyle(color: Color(0xFF666666),fontSize: 13.sp),),
                            SizedBox(height: 6.h,),
                            Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                Row(
                                  children: [
                                    _second(item),
                                    _fenqi(item)
                                  ],
                                ),
                                Row(
                                  children: [
                                    Text('¥',style: TextStyle(color: Color(0xFFFF0000),fontSize: 12.sp),),
                                    Text(item.sellPrice,style: TextStyle(color: Color(0xFFFF0000),fontSize: 18.sp),),
                                  ],
                                )
                              ],
                            )
                          ],
                        )
                    )
                  ],
                ),
                Container(
                  margin: EdgeInsets.only(top: 13.h,bottom: 13.h),
                  color: Color(0xFFF3F3F3),
                  height: 1.h,
                ),
                _btns(item),
                SizedBox(height: 11.h,)
              ],
            )
           ,
          )
      )
    ;
  }

  Widget _second(OrderListData item){
    String aa = '';
    if(item.isMsg == '2'){
      aa ='包人脸';
    }
    else if(item.isMsg == '1'){
      aa ='可二次';
    }else{
      aa ='不包人脸';
    }
    return Container(
      padding: EdgeInsets.only(left: 5.w,right: 5.w,top: 3.h,bottom: 3.h),
      decoration: BoxDecoration(
          border: Border.all(
            color: Color(0xFF007BE5), //边框颜色
            width: 1.w, //宽度
          ),
          borderRadius: BorderRadius.circular(5.r)
      ),
      child: Text(aa,style: TextStyle(
          color: Color(0xFF007BE5),
          fontSize: 8.sp
      ),),
    );
  }

  Widget _fenqi(OrderListData item){
    String aa = '不可分期';
    if(item.isBystages == '1'){
      aa ='可分期';
    }
    return Container(
      margin: EdgeInsets.only(left: 3.w),
      padding: EdgeInsets.only(left: 5.w,right: 5.w,top: 3.h,bottom: 3.h),
      decoration: BoxDecoration(
          border: Border.all(
            color: Color(0xFF007BE5), //边框颜色
            width: 1.w, //宽度
          ),
          borderRadius: BorderRadius.circular(5.r)
      ),
      child: Text(aa,style: TextStyle(
          color: Color(0xFF007BE5),
          fontSize: 8.sp
      ),),
    );
  }

  Widget _btns(OrderListData item){
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        Text(Common.transferDate(item.traTime),style: TextStyle(
          color: Color(0xFF999999),
          fontSize: 12.sp
        ),)  ,
        Row(
          children: [
            (item.status==15 || item.status==12|| item.status==13)?
            _btn('进入交易群组',item):Container(),
            item.status==12?
            _btn('换绑完成',item):Container(),
            item.status==11?
            _btn('取消订单',item):Container(),
            item.status==11?
            _btn('立即支付',item):Container(),
            item.status==13?
            _btn('确认收货',item):Container(),
          ],
        )
      ],
    );
  }



  Widget _btn(name,OrderListData item){
    return InkWell(
      onTap: (){
        if(name=='进入交易群组'){
          if(item.teamId.isEmpty){
            controller.getAddTeams(item);
          }else{
            controller._queryTeam(item.teamId);
          }

        }else if(name=='换绑完成'){
          controller._changeBind(context,item.channelId,item.id);
        }
        else if(name=='取消订单'){
          controller._cancelOrder(context,item.channelId,item.id);
        }else if(name=='立即支付'){
          _showSingle(item);
          // controller._buyNow(context,item.channelId,item.id);
        }else if(name=='确认收货'){
          controller._sureOrder(context,item.channelId,item.id);
        }
      },
      child:  Container(
        margin: EdgeInsets.only(right: 3.w),
        width: 80.w,
        height: 28.h,
        alignment: Alignment.center,
        decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(17.r),
            border: Border.all(width: 1.w,color: Color(0xFFC7C7C7))
        ),
        child: Text(name,style: TextStyle(
            color: const Color(0xFFC7C7C7),
            fontSize: 12.sp
        ),),
      )
    );
  }
  Future<Future<int?>> _showSingle(OrderListData item) async {
    return showModalBottomSheet<int>(
        backgroundColor: Colors.transparent,
        isScrollControlled: true,
        context: context,
        builder: (BuildContext context1) {
          return AnimatedPadding(
              padding: MediaQuery.of(context1).viewInsets, // 我们可以根据这个获取需要的padding
              duration: const Duration(milliseconds: 100),
              child:  Container(
                  height: 350.h,
                  padding: EdgeInsets.all(16.w),
                  clipBehavior: Clip.antiAlias,
                  decoration: const BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.only(
                      topLeft: Radius.circular(20.0),
                      topRight: Radius.circular(20.0),
                    ),
                  ),
                  child: Column(
                    children: [
                      Text('选择包赔类型',style: TextStyle(
                          color: Color(0xFF333333),
                          fontSize: 15.sp
                      ),),
                      SizedBox(height: 15.h,),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Row(
                            children: [
                              Image.asset( '${Constant.IMG_BASE}item_new.png',width: 24.w,height: 17.h,),
                              Text('普通包赔10%',style: TextStyle(
                                  color: Color(0xFF333333),
                                  fontSize: 16.sp,
                                  fontWeight: FontWeight.bold
                              ),)
                            ],
                          ),
                          Obx(() => InkWell(
                            onTap: (){
                              controller.baopeiRate.value = 0.1;
                              controller.update();
                            },
                            child:
                            controller.baopeiRate.value==0.1?
                            Image.asset( '${Constant.IMG_BASE}radio_yy.png',width: 18.w,height: 18.h,): Image.asset( '${Constant.IMG_BASE}icon_protect_n.png',width: 18.w,height: 18.h,),
                          )),


                        ],
                      ),
                      SizedBox(height: 10.h,),
                      Text('在下单购买账号时额外支付号价的10% (最低50元)，购买交易完成后，账号不转手 (换绑手机视为转手) 永久享受包赔服务，如出现账号找回情况，平台核实后在七天内进行处理，优先追回账号，超过七天未追回将全额退还支付号款，并对找回人员进行起诉追责处理!',
                        style: TextStyle(
                            color: Color(0xFF666666),
                            fontSize: 13.sp
                        ),),

                      SizedBox(height: 15.h,),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Row(
                            children: [
                              Image.asset( '${Constant.IMG_BASE}item_new.png',width: 24.w,height: 17.h,),
                              Text('2.5包赔20%',style: TextStyle(
                                  color: Color(0xFF333333),
                                  fontSize: 16.sp,
                                  fontWeight: FontWeight.bold
                              ),)
                            ],
                          ),
                          Obx(() => InkWell(
                            onTap: (){
                              controller.baopeiRate.value = 0.2;
                              controller.update();
                            },
                            child:
                            controller.baopeiRate.value==0.2?
                            Image.asset( '${Constant.IMG_BASE}radio_yy.png',width: 18.w,height: 18.h,): Image.asset( '${Constant.IMG_BASE}icon_protect_n.png',width: 18.w,height: 18.h,),
                          )),


                        ],
                      ),
                      SizedBox(height: 10.h,),
                      Text('在下单购买账号时额外支付号价的20% (最低100元)，交易完成后，账号不转手 (换绑手机视为转手) 永久享受2.5倍包赔服务，如出现账号找回情况，平台核实后在七天内进行处理，优先追回账号，超过七天未追回将全额退还支付号款，并对找回人员进行起诉追责处理!',
                        style: TextStyle(
                            color: Color(0xFF666666),
                            fontSize: 13.sp
                        ),),
                      SizedBox(height: 10.h,),
                      Container(
                        width: Get.width,
                        color: Color(0x0D000000),
                        height: 1.h,
                      ),
                      Container(
                          alignment: Alignment.center,
                          height: 53.h,
                          child:    Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Obx(() => Text('号价为${item.sellPrice}元，包赔费用${double.parse(item.sellPrice) *controller.baopeiRate.value}元',style: TextStyle(
                                  color: Color(0xFFFF0000),
                                  fontSize: 14.sp
                              ),))
                              ,
                              InkWell(
                                  onTap: (){
                                    double aa = double.parse(item.sellPrice) + double.parse(item.sellPrice) *controller.baopeiRate.value;
                                    Get.off(()=>ChargePage(),arguments: {
                                      'readOnly':true,
                                      'price':aa.toString(),
                                      'from':'buyNow',
                                      "channel_id":item.channelId,
                                      "goods_id":item.id.toString(),
                                    });
                                  },
                                  child: Container(
                                    alignment: Alignment.center,
                                    width: 104.w,
                                    height: 31.h,
                                    decoration: BoxDecoration(
                                        color: Color(0xFF007BE5),
                                        borderRadius: BorderRadius.all(Radius.circular(16.r))
                                    ),
                                    child: Text('立即支付',style: TextStyle(
                                        color: Colors.white,
                                        fontSize: 13.sp
                                    ),),
                                  )
                              )


                            ],
                          )
                      )

                    ],
                  )
              )
          ) ;
        });
  }


  Widget _officer() {
    return Container(
      child: Image.asset(Constant.IMG_BASE+'baopei.png',width: 52.w,height: 17.h,fit: BoxFit.fitWidth,),
    );
  }

}